import {PlusOutlined, EditOutlined, EyeOutlined, DeleteOutlined} from '@ant-design/icons';
import {Button, message, Modal} from 'antd';
import React, {useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import type {ActionType, ProColumns} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import SettingForm from './components/SettingForm';
import SettingDetail from './components/SettingDetail';
import {addSettingAPI, deleteSettingAPI, pageSettingAPI, updateSettingAPI} from "@/pages/system/setting/service";
import {downloadFileUrl, fullDownloadFileUrl} from "@/services/system/file";

const SettingManager: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentSetting, setCurrentSetting] = useState<API.ISetting | undefined>(undefined);

  const columns: ProColumns<API.ISetting>[] = [
    {
      title: '设置名称',
      dataIndex: 'name',
      width: 150,
      fixed: 'left',
    },
    {
      title: '配置键',
      dataIndex: 'settingKey',
      width: 200,
    },
    {
      title: '配置类型',
      dataIndex: 'settingType',
      width: 120,
      valueEnum: {
        'string': {text: '字符串'},
        'number': {text: '数值'},
        'boolean': {text: '布尔值'},
        'json': {text: 'JSON'},
        'file': {text: '文件'},
      },
    },
    {
      title: '配置值',
      dataIndex: 'settingValue',
      width: 200,
      ellipsis: true,
      render: (text, record) => {
        if (record.settingType === 'file') {
          return <a href={fullDownloadFileUrl(record.settingValue || '')} target="_blank"
                    rel="noopener noreferrer">查看文件</a>;
        }
        return text;
      },
    },
    {
      title: '操作',
      valueType: 'option',
      fixed: 'right',
      render: (_, record) => [
        <a
          key="view"
          onClick={() => {
            setCurrentSetting(record);
            setDetailVisible(true);
          }}
        >
          <EyeOutlined/> 查看
        </a>,
        <SettingForm
          key="edit"
          trigger={<a><EditOutlined/> 编辑</a>}
          initialValues={record}
          title={`编辑设置 - ${record.name}`}
          onFinish={async (values) => {
            try {
              const {data} = await updateSettingAPI({...values, id: record.id});
              if (data) {
                message.success('更新成功');
                actionRef.current?.reload();
              }
              return data;
            } catch (error) {
              message.error('更新失败');
              return false;
            }
          }}
        />,
        <a
          key="delete"
          style={{color: 'red'}}
          onClick={async () => {
            Modal.confirm({
              title: '确认删除',
              content: `确定要删除设置项 ${record.name} 吗？`,
              onOk: async () => {
                const {data} = await deleteSettingAPI(record.id || '');
                if (data) {
                  message.success('删除成功');
                  actionRef.current?.reload();
                }
                return data;
              },
            });
          }}
        >
          <DeleteOutlined/> 删除
        </a>,
      ],
    },
  ];

  return (
    <div style={{minHeight: '80vh'}} className={"protable-compact-wrapper"}>
      <ProTable<API.ISetting>
        columns={columns}
        actionRef={actionRef}
        request={async (params) => {
          const {data} = await pageSettingAPI(params);
          return data
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          span: 6,
        }}
        toolBarRender={() => [
          <SettingForm
            key="create"
            trigger={
              <Button type="primary">
                <PlusOutlined/> 新增设置
              </Button>
            }
            title="新增系统设置"
            onFinish={async (values) => {
              const {data} = await addSettingAPI(values);
              if (data) {
                message.success('添加成功');
                actionRef.current?.reload();
              }
              return data;
            }}
          />,
        ]}
      />

      <SettingDetail
        data={currentSetting || {}}
        visible={detailVisible}
        onClose={() => setDetailVisible(false)}
      />
    </div>
  );
};

export default SettingManager;
